import { Component, OnInit } from '@angular/core';

import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';

import { FinanceGatheringDetailService } from './finance-gathering-detail.service';
import { DatePipe } from '@angular/common';
import { CommonService } from 'src/app/services-common/common.service';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-finance-gathering-detail',
  templateUrl: './finance-gathering-detail.component.html',
  styleUrls: ['./finance-gathering-detail.component.scss'],
  providers: [DatePipe]
})
export class FinanceGatheringDetailComponent implements OnInit {
  isCollapse: boolean = false;

  // 搜索条件
  queryForms: any = {
    orderStateList: [], // 状态
    orderTimeArr: [], // 下单时间
    paymentTimeArr: [], // 付款时间
    shipTimeArr: [], // 发货时间
    dealTimeArr: [], // 完成时间
    payType: '', // 平台
    sourcePlatform: '', // 来源
    payOrderNum: '', // 交易流水
    supplierId: [] // 货主（供应商）
  };
  // table
  tableForms: any = {
    tableLoading: false,
    pageIndex: 1,
    pageSize: 20,
    total: 0
  };
  // tableData
  tableData: any = [];
  // model
  isVisible: boolean = false;
  // model title (订单号)
  modelTitle: string = '';
  // modelTabe
  modelTableData: any = [];

  // 订单状态数组：0-有效、1-无效、2-待付款、3-待审核、4-审核不通过、5-审核通过、6-排队发货、7-待发货、8-待收货（已发货）、9-交易完成、10-支付超时、11-客服取消、12-客户取消、13-售后中、14-全部退货
  statusArrys: any = [{
    id: 0,
    title: '有效'
  }, {
    id: 1,
    title: '无效'
  }, {
    id: 2,
    title: '待付款'
  }, {
    id: 3,
    title: '待审核'
  }, {
    id: 4,
    title: '审核不通过'
  }, {
    id: 5,
    title: '审核通过'
  }, {
    id: 6,
    title: '排队发货'
  }, {
    id: 7,
    title: '待发货'
  }, {
    id: 8,
    title: '待收货（已发货）'
  }, {
    id: 9,
    title: '交易完成'
  }, {
    id: 10,
    title: '支付超时'
  }, {
    id: 11,
    title: '客服取消'
  }, {
    id: 12,
    title: '客户取消'
  }, {
    id: 13,
    title: '售后中'
  }, {
    id: 14,
    title: '全部退货'
  }];

  // 订单来源
  orderSourceOptions: any = [];
  scurceSelected: any = [];

  // 货主options（供应商）
  supplierOptions: any = [];
  supplierSelected: any = [];

  exportLoading: boolean = false;

  constructor(
    private financeGatheringDetailService: FinanceGatheringDetailService,
    private message: NzMessageService,
    private datePipe: DatePipe,
    private commonService: CommonService,
    public permission: PermissionService,
    private modal: NzModalService
  ) { }

  async ngOnInit() {
    // 查询 订单来源平台
    this.orderSourceOptions = await this.commonService.getDictList('order_source_platform');
    this.querySupplierOptions();
    this.loadTableData()
  }

  // 查询货主
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.commonService.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name) || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 日期格式
  formatDate(date?: any) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }

  // loadData
  async loadTableData() {
    try {
      let datas = {
        orderStateList: this.queryForms.orderStateList,
        orderBeginTime: this.queryForms.orderTimeArr.length ? this.formatDate(this.queryForms.orderTimeArr[0]) : '',
        orderEndTime: this.queryForms.orderTimeArr.length ? this.formatDate(this.queryForms.orderTimeArr[1]) : '',
        paymentBeginTime: this.queryForms.paymentTimeArr.length ? this.formatDate(this.queryForms.paymentTimeArr[0]) : '',
        paymentEndTime: this.queryForms.paymentTimeArr.length ? this.formatDate(this.queryForms.paymentTimeArr[1]) : '',
        shipBeginTime: this.queryForms.shipTimeArr.length ? this.formatDate(this.queryForms.shipTimeArr[0]) : '',
        shipEndTime: this.queryForms.shipTimeArr.length ? this.formatDate(this.queryForms.shipTimeArr[1]) : '',
        dealBeginTime: this.queryForms.dealTimeArr.length ? this.formatDate(this.queryForms.dealTimeArr[0]) : '',
        dealEndTime: this.queryForms.dealTimeArr.length ? this.formatDate(this.queryForms.dealTimeArr[1]) : '',
        payType: this.queryForms.payType,
        sourcePlatform: this.queryForms.sourcePlatform,
        payOrderNum: this.queryForms.payOrderNum,
        supplierIdList: this.queryForms.supplierId, // 货主
        page: this.tableForms.pageIndex,
        pageSize: this.tableForms.pageSize
      }

      this.tableForms.tableLoading = true;
      const { data }: any = await this.financeGatheringDetailService.getTableData(datas);

      this.tableData = data.records || [];
      this.tableForms.total = data.total || 0;
      this.tableForms.tableLoading = false;
    } catch {
      this.tableForms.tableLoading = false;
    }
  }

  /**
   * 订单售后详情
   * @param orderNum 订单号
   */
  async getOrderModelTable(orderNum: number) {
    try {
      const params = {
        orderNum: orderNum
      }
      const { data }: any = await this.financeGatheringDetailService.getOrderTableData(params);
      this.modelTableData = data || [];
    } catch {
      // console.log('error');
    }
  }

  // 查询搜索
  queryTable() {
    this.tableForms.pageIndex = 1;
    this.loadTableData();
  }
  // 重置
  resetTable() {
    for (let key in this.queryForms) {
      if (Object.prototype.toString.call(this.queryForms[key]) === '[object Array]') {
        this.queryForms[key] = [];
      } else {
        this.queryForms[key] = '';
      }
    }
    this.queryForms.payType = '';
    this.queryForms.sourcePlatform = '';
    this.scurceSelected = [];
    this.supplierSelected = [];
    
    this.tableForms.pageIndex = 1;
    this.loadTableData();
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.pageIndex = index;
    this.loadTableData();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.pageIndex = 1;
    this.tableForms.pageSize = sizeNum;
    this.loadTableData();
  }

  showModal(orderNum: any) {
    this.modelTitle = '订单 ' + orderNum + ' 的售后详情' || '';
    this.isVisible = true;

    this.getOrderModelTable(orderNum)
  }
  
  handleOk(): void {
    this.isVisible = false;
  }
  
  handleCancel(): void {
    this.isVisible = false;
  }

  // 文件下载Blob
  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params: any = {
          orderStateList: String(this.queryForms.orderStateList),
          orderBeginTime: this.queryForms.orderTimeArr.length ? this.formatDate(this.queryForms.orderTimeArr[0]) : '',
          orderEndTime: this.queryForms.orderTimeArr.length ? this.formatDate(this.queryForms.orderTimeArr[1]) : '',
          paymentBeginTime: this.queryForms.paymentTimeArr.length ? this.formatDate(this.queryForms.paymentTimeArr[0]) : '',
          paymentEndTime: this.queryForms.paymentTimeArr.length ? this.formatDate(this.queryForms.paymentTimeArr[1]) : '',
          shipBeginTime: this.queryForms.shipTimeArr.length ? this.formatDate(this.queryForms.shipTimeArr[0]) : '',
          shipEndTime: this.queryForms.shipTimeArr.length ? this.formatDate(this.queryForms.shipTimeArr[1]) : '',
          dealBeginTime: this.queryForms.dealTimeArr.length ? this.formatDate(this.queryForms.dealTimeArr[0]) : '',
          dealEndTime: this.queryForms.dealTimeArr.length ? this.formatDate(this.queryForms.dealTimeArr[1]) : '',
          payType: this.queryForms.payType,
          payOrderNum: this.queryForms.payOrderNum,
          sourcePlatform: this.queryForms.sourcePlatform,
          supplierIdList: this.queryForms.supplierId, // 货主
          page: 1,
          pageSize: 1000000
        }
        Object.keys(params).map((item: any) => {
          if (!params[item]) {
               delete params[item];
           }
           return true;
        });
    
        this.exportLoading = true;
        const res: any = await this.financeGatheringDetailService.collectionExportTable(params);
        this.exportLoading = false;
        
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '收款明细');
        } else {
          this.message.error(res.message || '导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 订单来源平台change
  orderSourceChange(arrs: any) {
    this.queryForms.sourcePlatform = arrs.join(',');
  }

  /**
   * Dict类型转化文字
   * @returns
   */
  dictTextFilter(typeVal: String, arr: any) {
    let tmpObj: any = {};
    if (arr && arr.length) {
      tmpObj = arr.find((item: any) => item.content == typeVal);
    }

    return tmpObj?.name || '-';
  }

  // 多选Select Change
  multipleSelectChange(result: any, keyStr: string) {
    this.queryForms[keyStr] = result.join(',');
  }
}
